package com.zzyl.nursing.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.dto.DeviceDataPageReqDto;
import com.zzyl.nursing.dto.IotMsgNotifyData;
import com.zzyl.nursing.dto.IotMsgService;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.service.IDeviceDataService;
import com.zzyl.nursing.service.IDeviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 设备数据信息Service业务层处理
 * 
 * @author mr.wu
 * @date 2025-05-25
 */
@Slf4j
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    /**
     * 查询设备数据信息
     * 
     * @param id 设备数据信息主键
     * @return 设备数据信息
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备数据列表
     */
    @Override
    public Page selectDeviceDataList(DeviceDataPageReqDto dto)
    {
        Page<DeviceData> page = this.lambdaQuery()
                .eq(StringUtils.isNotBlank(dto.getDeviceId()), DeviceData::getIotId, dto.getDeviceId())
                .eq(StringUtils.isNotBlank(dto.getDeviceName()), DeviceData::getDeviceName, dto.getDeviceName())
                .eq(StringUtils.isNotBlank(dto.getFunctionId()), DeviceData::getFunctionId, dto.getFunctionId())
                .between(dto.getStartTime() != null && dto.getEndTime() != null, DeviceData::getAlarmTime, dto.getStartTime(), dto.getEndTime())
                .orderByDesc(DeviceData::getAlarmTime)
                .page(new Page<>(dto.getPageNum(), dto.getPageSize()));
        return page;
    }
    /**
     * 新增设备数据信息
     * 
     * @param deviceData 设备数据信息
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return save(deviceData) ? 1 : 0;
    }

    /**
     * 修改设备数据信息
     * 
     * @param deviceData 设备数据信息
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return updateById(deviceData) ? 1 : 0;
    }

    /**
     * 批量删除设备数据信息
     * 
     * @param ids 需要删除的设备数据信息主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备数据信息信息
     * 
     * @param id 设备数据信息主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    @Autowired
    private IDeviceService deviceService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 将获取到的设备上报数据进行解析，批量保存到设备数据表中
     *
     * @param contentStr
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void handleMessage(String contentStr) {
        //1. 判断数据是否为空
        if(StringUtils.isBlank(contentStr)) {
            throw new BaseException("数据非法");
        }

        JSONObject message = JSONUtil.parseObj(contentStr);
        JSONObject notifyDataObj = message.getJSONObject("notify_data");
        if(notifyDataObj==null) {
            throw new BaseException("数据非法");
        }

        JSONObject header = notifyDataObj.getJSONObject("header");
        JSONObject body = notifyDataObj.getJSONObject("body");
        if(header==null || body==null) {
            throw new BaseException("数据非法");
        }

        //2. 解析每一层数据
        IotMsgNotifyData notifyData = JSONUtil.toBean(notifyDataObj, IotMsgNotifyData.class);
        String deviceId = notifyData.getHeader().getDeviceId();//设备ID

        //3. 判断设备是否存在
        Device device = deviceService.lambdaQuery().eq(Device::getIotId, deviceId).one();
        if(device==null) {
            throw new BaseException("设备不存在");
        }

        //4. 设备数据封装
        List<IotMsgService> serviceList = notifyData.getBody().getServices();

        List<DeviceData> deviceDataList = new ArrayList<>();
        serviceList.forEach(x->{
            String eventTime = x.getEventTime();
            //设备上报数据的时间
            LocalDateTime alarmTime = OffsetDateTime
                    .parse(eventTime, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX"))
                    .atZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();

            Map<String, Object> properties = x.getProperties();
            properties.forEach((k,v)->{
                DeviceData data = new DeviceData();
                BeanUtils.copyProperties(device,data);
                data.setId(null);//必须设置为空，否则主键ID重复会出现问题
                data.setFunctionId(k); //功能名（设备物模型属性名）
                data.setDataValue(String.valueOf(v));//物模型属性值
                data.setAlarmTime(alarmTime);//上报时间
                data.setAccessLocation(device.getBindingLocation());//绑定位置（接入位置）
                deviceDataList.add(data);
            });
        });

        //4. 批量保存数据
        if(CollUtil.isNotEmpty(deviceDataList)){
            boolean result = this.saveBatch(deviceDataList);
            if(!result) {
                throw new BaseException("批量保存设备上报数据异常");
            }
            log.info("批量保存设备上报数据成功，本地保存成功{}条", deviceDataList.size());

            //5. 将设备最后一次上报的数据更新到Redis（Hash类型）
            redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA,deviceId,JSONUtil.toJsonStr(deviceDataList));
        }

    }


}
